<?php
/**
 * 红旭会数据导入
 * 用户头像
 * 积分商城图片
 * 会员活动图片
 */
namespace Tools\Controller;
use Common\Model\EventsModel;
use Common\Model\OtherSystem\jch;
use Common\Model\PointMallModel;
use Common\Model\UserModel;
use Common\Model\UtilsModel;
use Think\Controller;
class HxhController extends Controller {
    private $basePath='/home/wwwroot/www.hongxuhui.com/starjoy/data/outdata/';
    private $queryLog='/home/wwwroot/www.hongxuhui.com/starjoy/data/outdata/querylog';
    private $starDB = 'star_core';
    private $jchDB  = 'hongxuhui';
    private $oldHeadPath='/home/wwwroot/www.hongxuhui.com/czkAPI/public/img/user/head/';

    private $newContentImgPath="http://www.hongxuhui.com/czkAPI/admin/view/template2/js/ue/php/upload/image/";

    private $limit=999999999;

    const FIELD_SEPARATOR   ="@@@";
    const LINE_SEPARATOR    ="###";
    const ENCLOSED_SEPARATOR    ="~";

    public function index(){
        if(IS_CGI){
           // DIE("仅在cli模式下运行");
        }

        ini_set("memory_limit","-1");
        set_time_limit(0);





        file_put_contents($this->queryLog,date("Y-m-d H:i:s",time())."\r\n");
        ////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////
        //导入基础用户
       // $this->userBase();

        //微信
       // $this->userWeixin();


        //积分商城活动
        $this->pointMall();

        //积分商城兑换记录
        //$this->exchangeLog();


        //会员活动
        $this->event();
       // $this->eventJoin();
       //$this->creditLog();


        //评论相关
        $this->eventComment();
        $this->exchangeComment();
        display('---------------------------------------------------------');
        display('---------------------------------------------------------');
        display('---------------------全部合并完毕------------------------');
        die;
        

    }

    public function count(){
        $this->eventCommentCount();
        $this->exchangeCommentCount();
    }
    /**
     * 用户头像处理
     * Author: shijy
     */
    public function fixHeadImage(){
        $maxUid = M('user_info',null,SLAVE_CFG)->order('user_id desc')->limit(1)->getField('user_id');
        for($id=1;$id<=$maxUid;$id++){
            $oldFile=$this->oldHeadPath.$id.'.jpg';
            $newFile=USER_HEADPIC_SAVE_PATH.UserModel::getHeadPicPath($id);
            if(file_exists($oldFile)){
                UtilsModel::mkdir(dirname($newFile));
                copy($oldFile,$newFile);
            }
            display('处理'.$id);
        }

    }


    //基础数据
    private  function userBase(){
        $begin = microtime(true);
        $s_userM=M('user_info',null,SLAVE_CFG);
        $dataOuterFile=$this->basePath."userbase";

        unlink($dataOuterFile);
        $rawUser=$s_userM->field("user_id,nickname,sex,credit,rmb,`name`,phone_num,birthday,address,grade")->limit($this->limit)->select();

        $i=0;
        foreach ($rawUser as $one){
            $address=UtilsModel::formatAddress($one['address']);

            $tmp=array();
            $tmp[]=enclose($one['user_id']);
            $tmp[]=enclose($one['nickname']);
            $tmp[]=enclose($one['sex']);
            $tmp[]=enclose($one['credit']);
            $tmp[]=enclose($one['rmb']/100);
            $tmp[]=enclose($one['name']);
            $tmp[]=enclose($one['phone_num']);
            $tmp[]=enclose($one['birthday']);
            $tmp[]=enclose($address['newAddress']);
            $tmp[]=enclose($address['province']);
            $tmp[]=enclose($address['city']);
            $tmp[]=enclose($address['district']);
            $tmp[]=enclose($one['grade']);

            $str=implode(self::FIELD_SEPARATOR,$tmp).self::LINE_SEPARATOR;


            file_put_contents($dataOuterFile,$str,FILE_APPEND);
            $i++;
            display("导出第{$i}");
        }
        display("---------------------------------------------");
        display("----------------用户基础数据-----------------");

        $sql=<<<SQL
LOAD DATA LOCAL INFILE '%s' REPLACE INTO table %s.u_user_base FIELDS TERMINATED BY '%s' ENCLOSED BY '%s' LINES TERMINATED BY '%s' (
	`uid`,`nickname`,`sex`,`point`,`money`,`realName`,`bindPhone`,`birthday`,`address`,`province`,`city`,`district`,`vip`);
SQL;
        $sql=sprintf($sql,$dataOuterFile,$this->starDB,self::FIELD_SEPARATOR,self::ENCLOSED_SEPARATOR,self::LINE_SEPARATOR);



        $this->querylog("\r\n\r\n------用户数据------");
        $this->querylog($sql);

       // display('总共导入用户：'.(M('u_user_base',null,MASTER_CFG)->execute($sql)));
        $end = microtime(true);
        display('耗时'.round($end-$begin,3).'秒');
        $this->querylog('userBase耗时'.round($end-$begin,3).'秒');
    }

    //导入微信相关
    private function userWeixin(){
        $u_user_weixinM=M('u_user_weixin',null,MASTER_CFG);
        $u_user_weixinM->execute("truncate table {$this->starDB}.u_user_weixin");
        $u_user_weixinM->execute("INSERT INTO {$this->starDB}.u_user_weixin(uid,WX2_openID,WX1_subscribeTime) 
                                            SELECT user_id,open_id,UNIX_TIMESTAMP(focus_time) FROM {$this->jchDB}.user_info where LENGTH(open_id)>6");

        display("---------------------------------------------");
        display("----------------用户微信数据-----------------");
    }



    //会员活动
    private function event(){
        /**
         * jch的设定
         * status 1.待上线 2.已上线 3.逻辑删除
         *
         * todo 图片地址需要确认
         */
        $imgPre=$this->newContentImgPath;
        $begin = microtime(true);
        $m=M('active_rule',null,SLAVE_CFG);
        $dataOuterFile=$this->basePath."activeRule";
        unlink($dataOuterFile);
        $rawUser=$m->field("rq,display_time as showListTime,rule_id AS id,credit AS point,rmb AS price,title,s_title AS content,price AS originalPrice,num AS places,buy AS applyCount,address AS location
        ,unix_timestamp(start_time) AS beginShowTime,unix_timestamp(start_time) AS applyStartTime,unix_timestamp(end_time) AS applyEndTime,unix_timestamp(active_start_time) AS startTime,unix_timestamp(active_end_time) AS endTime,unix_timestamp(create_time) AS addTime")
            ->limit($this->limit)
            ->select();
        $i=0;
        foreach ($rawUser as $one){
            $content=preg_replace('/([\'"]+)\/jiaochenhuiAPI\/admin\/view\/js\/ue\/php\/upload\/image/i',"$1{$imgPre}",$one['content']);
            $content=str_replace('http://club.jiaochen.com.cn/jiaochenhuiAPI/admin/view/js/ue/php/upload/image/',$imgPre,$content);

            $listPic="http://www.hongxuhui.com/czkAPI/public/img/active/".$one['id'].'.jpg';
            $tmp=array();
            $tmp[]=enclose($one['rq']);
            $tmp[]=enclose($one['id']);
            $tmp[]=enclose($one['point']);
            $tmp[]=enclose($one['price']/100);
            $tmp[]=enclose($one['originalPrice']/100);
            $tmp[]=enclose($one['title']);
            $tmp[]=enclose($content);
            $tmp[]=enclose($one['places']);
            $tmp[]=enclose($one['applyCount']);
            $tmp[]=enclose($one['location']);
            $tmp[]=enclose($one['showListTime']);
            $tmp[]=enclose($one['startTime']);
            $tmp[]=enclose($one['endTime']);
            $tmp[]=enclose($one['beginShowTime']);
            $tmp[]=enclose($one['applyStartTime']);
            $tmp[]=enclose($one['applyEndTime']);
            $tmp[]=enclose($one['addTime']);
            $tmp[]=enclose($listPic);
            $clientShow=CLIENT_SHOW_WAP;
            $tmp[]=enclose($clientShow);
            
            $str=implode(self::FIELD_SEPARATOR,$tmp).self::LINE_SEPARATOR;
            file_put_contents($dataOuterFile,$str,FILE_APPEND);
            $i++;
            display("导出第{$i}");
        }

        display("---------------------------------------------------------------------");
        display("---------------------------会员活动----------------------------------");
        display("导出文件完成，下面开始导入");
        $sql=<<<SQL
LOAD DATA LOCAL INFILE '%s' REPLACE INTO TABLE %s.e_events FIELDS TERMINATED BY '%s' ENCLOSED BY '%s' LINES TERMINATED BY '%s' (
	`hot`,`id`,`point`,`price`,`originalPrice`,`title`,`content`,`places`,`applyCount`,`location`,`showListTime`,
	`startTime`,`endTime`,`beginShowTime`,`applyStartTime`,`applyEndTime`,`addTime`,`imgList`,`clientShow`);
SQL;
        $sql=sprintf($sql,$dataOuterFile,$this->starDB,self::FIELD_SEPARATOR,self::ENCLOSED_SEPARATOR,self::LINE_SEPARATOR);

        $this->querylog("\r\n\r\n------会员活动------");
        $this->querylog($sql);
        //display('总共导入记录：'.($m->execute($sql)));

        $end = microtime(true);
        display('耗时'.round($end-$begin,3).'秒');
        $this->querylog('event耗时'.round($end-$begin,3).'秒');
    }
    private function eventJoin(){
        $begin = microtime(true);
        $m=M('active_log',null,SLAVE_CFG);
        $dataOuterFile=$this->basePath."activeLog";
        unlink($dataOuterFile);
        $rawUser=$m->field("log_id as id,rule_id as eid ,user_id as uid,UNIX_TIMESTAMP(create_time) as addTime,`name` as realName,phone_num as phone,`status`,msg as mark")
            ->limit($this->limit)
            ->select();
        $i=0;
        foreach ($rawUser as $one){
            $tmp=array();
            $tmp[]=enclose($one['id']);
            $tmp[]=enclose($one['eid']);
            $tmp[]=enclose($one['uid']);
            $tmp[]=enclose($one['addTime']);
            $tmp[]=enclose($one['realName']);
            $tmp[]=enclose($one['phone']);
            $tmp[]=enclose($one['mark']);
            //Status 1.待审核，2.入选。3.淘汰 4.已享用
            switch ($one['status']+0){
                case 1:
                    $status=EventsModel::JOIN_STATUS_APPLY;
                    break;
                case 2:
                    $status=EventsModel::JOIN_STATUS_SELECTED;
                    break;
                case 3:
                    $status=EventsModel::JOIN_STATUS_UNSELECTED;
                    break;
                case 4:
                    $status=EventsModel::JOIN_STATUS_SELECTED;
                    break;
            }
            $tmp[]=enclose($status);



            $str=implode(self::FIELD_SEPARATOR,$tmp).self::LINE_SEPARATOR;
            file_put_contents($dataOuterFile,$str,FILE_APPEND);
            $i++;
            display("导出第{$i}");

        }

        display("---------------------------------------------------------------------");
        display("-----------------------会员活动报名相关------------------------------");
        display("导出文件完成，下面开始导入");
        $sql=<<<SQL
LOAD DATA LOCAL INFILE '%s' REPLACE INTO TABLE %s.e_events_join FIELDS TERMINATED BY '%s' ENCLOSED BY '%s' LINES TERMINATED BY '%s' (
	`id`,`eid`,`uid`,`addTime`,`realName`,`phone`,`mark`,`status`);
SQL;
        $sql=sprintf($sql,$dataOuterFile,$this->starDB,self::FIELD_SEPARATOR,self::ENCLOSED_SEPARATOR,self::LINE_SEPARATOR);

        $this->querylog("\r\n\r\n------会员活动报名------");
        $this->querylog($sql);

        //display('总共导入记录：'.($m->execute($sql)));

        $end = microtime(true);
        display('耗时'.round($end-$begin,3).'秒');
        $this->querylog('eventJoin耗时'.round($end-$begin,3).'秒');
    }

    private function querylog($content){
        file_put_contents($this->queryLog,"\r\n\r\n".$content."\r\n",FILE_APPEND);
    }
    //活动评论
    private function eventComment(){
        $begin = microtime(true);
        $m=M('active_comment_info',null,SLAVE_CFG);
        $dataOuterFile=$this->basePath."activeComment";
        unlink($dataOuterFile);
        $rawUser=$m->field("comment_id as id,user_id as uid,content,active_id as objID,UNIX_TIMESTAMP(create_time) as addTime")
            ->where('type_id=1')
            ->limit($this->limit)
            ->select();

        $i=0;
        foreach ($rawUser as $one){
            $tmp=array();
            $tmp[]=enclose($one['id']);
            $tmp[]=enclose($one['uid']);

           // $tmp[]=enclose(mb_convert_encoding($one['content'],"utf8mb4","UTF-8"));
            $tmp[]=enclose($one['content']);
            $tmp[]=enclose($one['objID']);
            $tmp[]=enclose(OBJ_TYPE_ACTIVITY);
            $tmp[]=enclose($one['addTime']);
            $str=implode(self::FIELD_SEPARATOR,$tmp).self::LINE_SEPARATOR;
            file_put_contents($dataOuterFile,$str,FILE_APPEND);
            $i++;
            display("导出第{$i}");

        }

        display("---------------------------------------------------------------------");
        display("--------------------------会员活动评论-------------------------------");
        display("导出文件完成，下面开始导入");
        $sql=<<<SQL
LOAD DATA LOCAL INFILE '%s' REPLACE INTO TABLE %s.comment_2 FIELDS TERMINATED BY '%s' ENCLOSED BY '%s' LINES TERMINATED BY '%s' (
	`id`,`uid`,`content`,`objID`,`objType`,`addTime`);
SQL;
        $sql=sprintf($sql,$dataOuterFile,$this->starDB,self::FIELD_SEPARATOR,self::ENCLOSED_SEPARATOR,self::LINE_SEPARATOR);

        $this->querylog('------会员活动评论------');
        $this->querylog($sql);

        //display('总共导入记录：'.($m->execute($sql)));
        $end = microtime(true);
        display('耗时'.round($end-$begin,3).'秒');
        $this->querylog('eventComment耗时'.round($end-$begin,3).'秒');

    }

    //活动评论统计
    private function eventCommentCount(){

        $sql=<<<SQL
select objID,count(1) as commentNum2
from comment_2 group by objID
SQL;


        display("---------------------------------------------------------------------");
        display("--------------------------同步活动评论统计-------------------------------");
        $m=M('comment_'.OBJ_TYPE_ACTIVITY,NULL,MASTER_CFG);
        $commentCount=$m->group('objID')->field('objID,count(1) as commentNum')->select();
        $sql="update e_events set commentNum= case id ";
        $case=array();
        foreach($commentCount as $one){
            $case[]="when {$one['objID']} then {$one['commentNum']} ";
        }
        $sql.=implode($case).'end';
        $m->execute($sql);
    }
    //兑换评论
    private function exchangeComment(){
        $begin = microtime(true);
        $m=M('active_comment_info',null,SLAVE_CFG);
        $dataOuterFile=$this->basePath."exchangeComment";
        unlink($dataOuterFile);
        $rawUser=$m->field("comment_id as id,user_id as uid,content,active_id as objID,UNIX_TIMESTAMP(create_time) as addTime")
            ->where('type_id=2')
            ->limit($this->limit)
            ->select();
        $i=0;
        foreach ($rawUser as $one){
            $tmp=array();
            $tmp[]=enclose($one['id']);
            $tmp[]=enclose($one['uid']);
            $tmp[]=enclose($one['content']);
            $tmp[]=enclose($one['objID']);
            $tmp[]=enclose(OBJ_TYPE_POINTMALL);
            $tmp[]=enclose($one['addTime']);
            $str=implode(self::FIELD_SEPARATOR,$tmp).self::LINE_SEPARATOR;
            file_put_contents($dataOuterFile,$str,FILE_APPEND);
            $i++;
            display("导出第{$i}");

        }

        display("---------------------------------------------------------------------");
        display("------------------------积分商城评论---------------------------------");
        display("导出文件完成，下面开始导入");
        $sql=<<<SQL
LOAD DATA LOCAL INFILE '%s' REPLACE INTO TABLE %s.comment_4 FIELDS TERMINATED BY '%s' ENCLOSED BY '%s' LINES TERMINATED BY '%s' (
	`id`,`uid`,`content`,`objID`,`objType`,`addTime`);
SQL;
        $sql=sprintf($sql,$dataOuterFile,$this->starDB,self::FIELD_SEPARATOR,self::ENCLOSED_SEPARATOR,self::LINE_SEPARATOR);

        $this->querylog('------积分商城评论------');
        $this->querylog($sql);
        //display('总共导入记录：'.($m->execute($sql)));
        $end = microtime(true);
        display('耗时'.round($end-$begin,3).'秒');
        $this->querylog('exchangeComment耗时'.round($end-$begin,3).'秒');
    }
    private function exchangeCommentCount(){

        display("---------------------------------------------------------------------");
        display("--------------------------同步积分兑换评论统计-------------------------------");
        $m=M('comment_'.OBJ_TYPE_POINTMALL,NULL,MASTER_CFG);
        $commentCount=$m->group('objID')->field('objID,count(1) as commentNum')->select();
        $sql="update point_mall set commentNum= case id ";
        $case=array();
        foreach($commentCount as $one){
            $case[]="when {$one['objID']} then {$one['commentNum']} ";
        }
        $sql.=implode($case).'end';
        $m->execute($sql);
    }

    //积分日志
    private function creditLog(){
        $begin = microtime(true);
        $m=M('credit_log',null,SLAVE_CFG);
        $dataOuterFile=$this->basePath."creditLog";
        unlink($dataOuterFile);
        $count=$m->getField('count(1)');
        $pageSize=100000;
        $pageCount=ceil($count/$pageSize);
        for($p=0;$p<$pageCount;$p++) {
            $offset=$p*$pageSize;
            $rawUser = $m->field("log_id AS id,user_id AS uid,rule_id AS action,UNIX_TIMESTAMP(create_time) AS addTime,flag AS addOrReduce,num AS changeVal,pre_num,`desc`")
                ->limit($offset,$pageSize)
                ->select();
            $i = $offset;
            foreach ($rawUser as $one) {
                $tmp = array();
                $tmp[] = enclose($one['id']);
                $tmp[] = enclose($one['uid']);
                $tmp[] = enclose($one['changeVal']);
                $tmp[] = enclose($one['addTime']);
                $tmp[] = enclose($one['desc']);

                if ($one['addOrReduce'] == 1) {//1表示增加，其它都表示扣除
                    $addOrReduce = VAL_ADD;
                    $finalVal = $one['pre_num'] + $one['changeVal'];
                } else {
                    $addOrReduce = VAL_REDUCE;
                    $finalVal = $one['pre_num'] - $one['changeVal'];
                }
                $tmp[] = enclose($addOrReduce);
                $tmp[] = enclose($finalVal);

                $action = jch::actionSwitch_Jch_StarJoy($one['action']);
                $tmp[] = enclose($action);
                $str = implode(self::FIELD_SEPARATOR, $tmp) . self::LINE_SEPARATOR;
                file_put_contents($dataOuterFile, $str, FILE_APPEND);
                $i++;
                display("导出第{$i}");

            }
            unset($rawUser);
        }

        display("---------------------------------------------------------------------");
        display("------------------------积分日志-------------------------------------");
        display("导出文件完成，下面开始导入");
        $sql=<<<SQL
LOAD DATA LOCAL INFILE '%s' REPLACE INTO TABLE %s.u_point_log FIELDS TERMINATED BY '%s' ENCLOSED BY '%s' LINES TERMINATED BY '%s' (
	`id`,`uid`,`changeVal`,`addTime`,`desc`,`addOrReduce`,`finalVal`,`act`);
SQL;
        $sql=sprintf($sql,$dataOuterFile,$this->starDB,self::FIELD_SEPARATOR,self::ENCLOSED_SEPARATOR,self::LINE_SEPARATOR);

        $this->querylog('------积分日志------');
        $this->querylog($sql);
        //display('总共导入记录：'.($m->execute($sql)));
        $end = microtime(true);
        display('耗时'.round($end-$begin,3).'秒');
        $this->querylog('creditLog耗时'.round($end-$begin,3).'秒');

    }


    //积分商城
    private function pointMall(){
        /**
         * jch的设定
         * type 1.需发货 2.卡券 3.电子券 4.流量
         * status 1.上线 2.删除 3.待上线
         *
         * todo 图片地址需要确认
         */
        $imgPre=$this->newContentImgPath;
        $begin = microtime(true);
        $m=M('exchange_rule',null,SLAVE_CFG);
        $dataOuterFile=$this->basePath."exchangeRule";
        unlink($dataOuterFile);
        $m->execute("truncate table {$this->starDB}.point_mall");
        $rawUser=$m->field("status,rule_id as id,credit as point,rmb as nowPrice,title,s_title as content,unix_timestamp(start_time) as beginShowTimestamp,unix_timestamp(end_time) as endExchangeTimestamp,
        price as originalPrice,num as stock,buy as buyNum,create_time as updateTime,max_num as quota,`sort` as showOrder,`type`")
            ->limit($this->limit)
            ->select();

        $i=0;
        foreach ($rawUser as $one){

            $content=preg_replace('/([\'"]+)\/jiaochenhuiAPI\/admin\/view\/js\/ue\/php\/upload\/image/i',"$1{$imgPre}",$one['content']);
            $content=str_replace('http://club.jiaochen.com.cn/jiaochenhuiAPI/admin/view/js/ue/php/upload/image/',$imgPre,$content);

            $cover="http://www.hongxuhui.com/czkAPI/public/img/credit/".$one['id'].'_thum.jpg';
            $listPic="http://www.hongxuhui.com/czkAPI/public/img/credit/".$one['id'].'_thum.jpg';
            $tmp=array();
            $tmp[]=enclose($one['id']);
            $tmp[]=enclose($one['point']);
            $tmp[]=enclose($one['nowPrice']/100);
            $tmp[]=enclose($one['title']);
            $tmp[]=enclose($one['title']);
            $tmp[]=enclose($content);
            $tmp[]=enclose($one['beginShowTimestamp']);
            $tmp[]=enclose($one['endExchangeTimestamp']);
            $tmp[]=enclose($one['originalPrice']);
            $tmp[]=enclose($one['stock']);
            $tmp[]=enclose($one['buyNum']);
            $tmp[]=enclose($one['updateTime']);
            $tmp[]=enclose($one['quota']);
            $tmp[]=enclose($one['showOrder']);
            $tmp[]=enclose($cover);
            $tmp[]=enclose($listPic);


           // status 1.上线 2.删除 3.待上线
            if ($one['status']==1){
                $status=PointMallModel::POINTMALL_IS_ONLINE;
            }else{
                $status=PointMallModel::POINTMALL_IS_PREPARE;
            }
            $tmp[]=enclose($status);



            //type 1.需发货 2.卡券 3.电子券 4.流量
            switch($one['type']+0){
                case 1:
                    $deliveryType=PointMallModel::DELIVERY_SEND;
                    break;
                case 2:
                case 3:
                    $deliveryType=PointMallModel::DELIVERY_CARD;
                    break;
                case 4:
                    $deliveryType=PointMallModel::DELIVERY_TRAFFIC;
                    break;
            }
            $tmp[]=enclose($deliveryType);
            $actionType=PointMallModel::ACTION_EXCHANGE;
            $tmp[]=enclose($actionType);

            $clientShow=CLIENT_SHOW_WAP;
            $tmp[]=enclose($clientShow);



            $str=implode(self::FIELD_SEPARATOR,$tmp).self::LINE_SEPARATOR;
            file_put_contents($dataOuterFile,$str,FILE_APPEND);
            $i++;
            display("导出第{$i}");

        }

        display("---------------------------------------------------------------------");
        display("------------------------积分商城-------------------------------------");
        display("导出文件完成，下面开始导入");
        $sql=<<<SQL
LOAD DATA LOCAL INFILE '%s' REPLACE INTO TABLE %s.point_mall FIELDS TERMINATED BY '%s' ENCLOSED BY '%s' LINES TERMINATED BY '%s' (
	`id`,`point`,`nowPrice`,`titleList`,`titleInner`,`content`,`beginShowTimestamp`,`endExchangeTimestamp`,`originalPrice`,`stock`
	,`buyNum`,`updateTime`,`quota`,`showOrder`,`cover`,`listPic`,`status`,`deliveryType`,`actionType`,`clientShow`);
SQL;
        $sql=sprintf($sql,$dataOuterFile,$this->starDB,self::FIELD_SEPARATOR,self::ENCLOSED_SEPARATOR,self::LINE_SEPARATOR);

        $this->querylog("\r\n\r\n------积分商城数据------");
        $this->querylog($sql);
        //display('总共导入记录：'.($m->execute($sql)));

        $end = microtime(true);
        display('耗时'.round($end-$begin,3).'秒');
        $this->querylog('pointMall耗时'.round($end-$begin,3).'秒');

    }

    //积分商城 日志
    private function exchangeLog(){
        $begin = microtime(true);
        $m=M('exchange_log',null,MASTER_CFG);
        $m->execute("truncate table {$this->starDB}.exchange_log");
        $m->execute("
        insert into {$this->starDB}.exchange_log(id,uid,pid,exchangeTime,address,realName,phone)
        select log_id as id,user_id as uid,rule_id as pid,unix_timestamp(create_time) as exchangeTime
                ,address,name as realName,phone_num as phone
            from {$this->jchDB}.exchange_log where 1
        ");

        $end = microtime(true);
        display("----------------------------------------------");
        display("---------------积分商城兑换日志---------------");
        display("积分商城兑换日志导入完成");
        $this->querylog('exchangeLog耗时'.round($end-$begin,3).'秒');
    }

    public function getRegionByName($name)
    {
        $rid = $cid = $aid = 0;
        list($r, $c, $a) = explode('|',$name);
        if($r) $rid = self::getRegion($r);
        if($r && $c) $cid = self::getRegion($c, $rid);
        if($r && $c && $a) $aid = self::getRegion($a, $cid);

        return array('province'=>$rid, 'city'=> $cid, 'district'=>$aid);
    }

    public function getRegion($r, $c){
        $re = C("REGION");
        foreach ($re as $val){
            if($c) {
                if ($val[2] == $r && $c == $val[1]) {
                    return $val[0];
                    break;
                }
            }else{
                if ($val[2] == $r) {
                    return $val[0];
                    break;
                }
            }
        }

    }

    public function ajaxUpload(){
        $this->ajaxReturn(self::imageUpload('file',C('FILE_UPLOAD_DIR')));
    }

    /**
     * 上传图片
     * @param string $photo_field_nam,form中存放图片的字段名
     * @param string $rootPath 以站点根目录开始，以/开始,以/结尾
     * @return array(
     *      id,0表示出错，其他值表示正确
     *      msg，出错时为提示信息，图片存放路径
     * )
     */
    private function imageUpload($photo_field_name = 'photo',$rootPath = ''){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小 3*1024*1024 3M
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = '.'.$rootPath; // 设置附件上传根目录

        $return=array('id'=>0,'msg'=>'');
        // 上传单个文件
        $info = $upload->uploadOne($_FILES[$photo_field_name]);

        if(!$info) {// 上传错误提示错误信息
            $return['msg']=$upload->getError();
        }else{// 上传成功 获取上传文件信息

            $newMD5     = $info['md5'];
            $photoLib   = M('photo_lib',null,MASTER_CFG);
            $existPhoto = $photoLib->where(array('md5'=>$newMD5))->find();
            $fullPath   = $rootPath.$info['savepath'].$info['savename'];
            if($existPhoto){
                @unlink ('./'.$fullPath);
                $existPhoto['ref'] +=1;
                $photoLib->save($existPhoto);
                $return= array('id'=>$existPhoto['id'],'msg'=>$existPhoto['path']);
            }else{
                $result=$photoLib->add(array('path'=>$fullPath,'md5'=>$newMD5,'ref'=>1));
                if($result!==false){
                    $return= array('id'=>$result,'msg'=>$fullPath);
                }
            }

        }
        return $return;
    }

    // base64图片上传
    public function base64upload() {
        $dataURL = $_POST['dataURL'];
        list($mime, $data) = explode(',', $dataURL);
        $blob = base64_decode($data);
        $mime_array = explode(';', $mime);
        $mime_array = $mime_array[0];
        $extName=explode('/', $mime_array);
        $extName = $extName[1];

        $rootPath=C('FILE_UPLOAD_DIR');
        $result = $this->UploadImage($blob,$rootPath,$extName);
        if ($result) {
            return print(json_encode(array('status' => 0, 'url' => $result)));
        }
        return print(json_encode(array('status' => 1)));
    }

    //图片上传
    private function UploadImage($blob, $direct,$extName='.jpg') {
        if($extName[0]!='.')
        {
            $extName ='.'.$extName;
        }

        $direct.=date('Y-m-d/');
        $name=date('His_').rand(1,1000).$extName;
        //创建目录
        $dirpath=WEB_ROOT.$direct;

        if(!is_dir($dirpath)){
            if(!mkdir($dirpath, 0777, true)){
                return "";
            }
        }

        file_put_contents(WEB_ROOT.$direct.$name, $blob);//返回的是字节数printr(a);
        $newMD5=md5_file(WEB_ROOT.$direct.$name);
        $photoLib   = M('photo_lib',null);
        $existPhoto = $photoLib->where(array('md5'=>$newMD5))->find();

        $fullPath   = $direct.$name;// $rootPath.$info['savepath'].$info['savename'];

        if($existPhoto){
            @unlink (WEB_ROOT.$direct.$name);
            $existPhoto['ref'] += 1;
            $photoLib->save($existPhoto);
            $return= $existPhoto['path'];
        }else{
            $result=$photoLib->add(array('path'=>$fullPath,'md5'=>$newMD5,'ref'=>1));
            if($result!==false){
                $return= $fullPath;
            }
        }
        return $return;
    }

}





function display($str){
    echo $str."\n\r";
    @ob_flush();@flush();
}

function enclose($str){
    return HxhController::ENCLOSED_SEPARATOR.$str.HxhController::ENCLOSED_SEPARATOR;
}